package com.xuan.chatroom.utils;

import com.xuan.chatroom.constants.Constant;
import com.xuan.chatroom.model.User;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtil {

    // 设置3小时的过期时间
    private final static long expirationTime = 1000 * 60 * 60 * 3;
    private final static String secretString = "wB3zS7d+rqJFxlP1AlSym4VAZhrakaLbcjSmkQ6Qrug=";
    private final static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    // 生成令牌
    public static String geneToken(Map<String, Object> claim) {
        String token = Jwts.builder().addClaims(claim)                                  // 设置自定义信息
                .setExpiration(new Date(System.currentTimeMillis() + expirationTime))   // 设置过期时间
                .signWith(key)                                                          // 添加密钥
                .compact();
        return token;
    }


//    public void geneSecreteString() {
//        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
//        String secretString = Encoders.BASE64.encode(secretKey.getEncoded());
//        System.out.println(secretString);
//    }

    // 解析令牌
    public static Claims parseToken(String token) {
        JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(key).build();  // 获得token解析器
        Claims claims = null;
        try {
            claims = jwtParser.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            log.error("令牌过期，校验失败! token: " + token);
        } catch (Exception e) {
            log.error("令牌校验失败! token: " + token);
        }
        return claims;
    }

    public static Integer getIdFromToken(String token) {
        return (Integer) parseToken(token).get(Constant.CLAIM_USERID);
    }
    public static String getUserNameFromToken(String token) {
        return (String) parseToken(token).get(Constant.CLAIM_USERNAME);
    }
}
